﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHouse.StorageForm;

namespace BW.Mes.WinForms.WareHouse
{
    public partial class StorageLocationForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _wareHouseApiBaseUrl = "http://120.26.197.100:8022";
        private List<StorageLocationModel> _allWareHouse; // 存储所有数据

        public StorageLocationForm()
        {
            InitializeComponent();
            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 窗体加载时获取数据
            this.Load += StorageLocationForm_Load;

            // 注册分页控件事件
            userControl11.ClickPageButtonEvent += UserControl1_ClickPageButtonEvent;
            userControl11.ChangedPageSizeEvent += UserControl1_ChangedPageSizeEvent;
            userControl11.JumpPageEvent += UserControl1_JumpPageEvent;
        }

        private async void StorageLocationForm_Load(object sender, EventArgs e)
        {
            await LoadStorageLocationData();
            DisplayPagedData();
        }


        // 加载仓库数据
        private async Task LoadStorageLocationData()
        {
            try
            {
                _allWareHouse = await GetApiDataAsync<List<StorageLocationModel>>("T3/Storagelocation/GetStoragelocation");

                //// 设置总记录数和总页数
                userControl11.TotalRows = _allWareHouse.Count;
                userControl11.TotalPages = (int)Math.Ceiling((double)_allWareHouse.Count / userControl11.PageSize);

                // 更新页码信息标签
                userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";


                // 确保清除旧数据源并重新设置
                gridControl1.DataSource = null;
                gridControl1.DataSource = _allWareHouse;

                // 确保网格视图显示数据
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();


            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }

        // 显示分页后的数据
        private void DisplayPagedData()
        {
            if (_allWareHouse == null || _allWareHouse.Count == 0)
                return;

            int startIndex = (userControl11.CurrentPage - 1) * userControl11.PageSize;
            int count = Math.Min(userControl11.PageSize, _allWareHouse.Count - startIndex);

            if (startIndex < 0 || count <= 0)
                return;

            // 获取当前页的数据
            var pagedData = _allWareHouse.Skip(startIndex).Take(count).ToList();

            // 绑定到GridControl
            gridControl1.DataSource = null;
            gridControl1.DataSource = pagedData;

            // 刷新网格视图
            gridView1.BestFitColumns();
            gridView1.RefreshData();
        }

        // 页码按钮点击事件处理
        private void UserControl1_ClickPageButtonEvent(int currentPage)
        {
            DisplayPagedData();
        }

        // 每页显示条数改变事件处理
        private void UserControl1_ChangedPageSizeEvent()
        {
            // 重新计算总页数
            userControl11.TotalPages = (int)Math.Ceiling((double)_allWareHouse.Count / userControl11.PageSize);
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";
            DisplayPagedData();
        }

        // 跳转页面事件处理
        private void UserControl1_JumpPageEvent(int jumpPage)
        {
            DisplayPagedData();
        }

        // 获取库位设置
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_wareHouseApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 调试显示原始响应内容
                Console.WriteLine($"API响应: {responseBody}");

                // 先解析为JObject以便提取内部数据
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                // 假设数组数据在"data"字段中
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    Console.WriteLine($"提取的pageDatas字段: {dataJson}");

                    return JsonConvert.DeserializeObject<T>(dataJson);
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
                return default;
            }
        }



        // 定义货架/库区模型类
        public class StorageLocationModel
        {
            public bool IsSelect { get; set; }
            [DisplayName("序号")]
            public long Id { get; set; }
            /// <summary>
            /// 库位编码
            /// </summary>
            [DisplayName("编码")]
            public string StorageLocationCoding { get; set; }
            /// <summary>
            /// 库位名称
            /// </summary>
            [DisplayName("名称")]
            public string StorageLocationName { get; set; }
            /// <summary>
            /// 货架/库区id
            /// </summary>
            [DisplayName("货架/库区id")]
            public long StorageId { get; set; }
            [DisplayName("货架/库区名称")]
            public string StorageName { get; set; }
           

            [DisplayName("描述")]
            public string StorageLocationDescribe { get; set; }

            
        }

        // 操作后刷新数据按钮的事件处理
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            LoadStorageLocationData();
        }




        /// <summary>
        /// 删除点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void StorageDeleteButton3_Click(object sender, EventArgs e)
        {
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelect");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;
                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;
                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要删除的行！");
                return;
            }
            if (XtraMessageBox.Show($"确认删除选中的 {checkedIds.Count} 条记录？", "批量删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            using (var client = new HttpClient { BaseAddress = new Uri(_wareHouseApiBaseUrl) })
            {
                foreach (var id in checkedIds)
                {
                    var resp = await client.PostAsync($"/T3/Storagelocation/DeleteStoragelocation?Id={id}", new StringContent("", Encoding.UTF8, "application/json"));
                    if (!resp.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"删除 Id={id} 失败：{resp.ReasonPhrase}");
                        return;
                    }
                }
            }

            XtraMessageBox.Show("删除完成！");
            // 刷新数据
            await LoadStorageLocationData();
            DisplayPagedData();
        }

        /// <summary>
        /// 添加货架/库区的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            var createForm = new CreateStorageLocationForm();
            createForm.StorageLocationAdded += CreateForm_StorageAdded;
            createForm.ShowDialog();
        }

        /// <summary>
        /// 自动刷新事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateForm_StorageAdded(object sender, EventArgs e)
        {
            // 刷新父窗体数据
            LoadStorageLocationData(); // 假设这是加载数据的方法
        }
        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            CreateStorageLocationForm createStorageLocationForm = new CreateStorageLocationForm();
            createStorageLocationForm.Show();

        }

        private void simpleButton4_Click_1(object sender, EventArgs e)
        {
            // 获取选中的行ID
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelect");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;

                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;

                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }

            // 检查是否只选中了一行
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要编辑的行！", "提示");
                return;
            }
            else if (checkedIds.Count > 1)
            {
                XtraMessageBox.Show("一次只能编辑一条记录，请只勾选一行！", "提示");
                return;
            }

            // 只有一个ID被选中，打开编辑窗口
            long selectedId = checkedIds[0];
            UpdateStorageLocationForm updateStorage = new UpdateStorageLocationForm(selectedId);

            // 使用ShowDialog使窗口模态显示，并获取结果
            if (updateStorage.ShowDialog() == DialogResult.OK)
            {
                // 如果编辑成功，刷新数据
                LoadStorageLocationData().ContinueWith(t =>
                {
                    // 在UI线程上执行
                    this.Invoke(new Action(() =>
                    {
                        DisplayPagedData();
                    }));
                });
            }
        }
        /// <summary>
        /// 库位设置导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton3_Click(object sender, EventArgs e)
        {
            try
            {
                // 显示等待提示
                using (var wait = new DevExpress.Utils.WaitDialogForm("正在导出数据，请稍候...", "导出中"))
                {
                    // 调用后端导出API
                    HttpResponseMessage response = await _httpClient.GetAsync($"{_wareHouseApiBaseUrl}/T3/Storagelocation/Derive");
                    response.EnsureSuccessStatusCode();

                    // 获取文件内容
                    byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

                    // 使用保存对话框让用户选择保存位置
                    SaveFileDialog saveDialog = new SaveFileDialog
                    {
                        Filter = "Excel文件|*.xlsx|所有文件|*.*",
                        FileName = $"库位设置数据_{DateTime.Now:yyyyMMdd}.xlsx",
                        Title = "保存导出文件"
                    };

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        // 保存文件
                        System.IO.File.WriteAllBytes(saveDialog.FileName, fileBytes);
                        XtraMessageBox.Show("数据导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}